import "package:flutter/material.dart";
import "package:get/get.dart";
import "package:r_upgrade/r_upgrade.dart";
import "package:sn_progress_dialog/progress_dialog.dart";

import '../../components/appbar_widget/appbar_widget.dart';
import '../../config/global_config.dart';
import 'components/tips_widget.dart';

class Update extends StatefulWidget {
  @override
  UpdateState createState() => new UpdateState();
}

class UpdateState extends State<Update> {
  // 状态码：0：等待安装/1：安装失败/2：权限不足/2+ 正常情况
  int state = 99;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget("应用更新", isMore: false).build(context),
      body: Center(child: TipsWidget(state)),
    );
  }

  /// app更新
  /// * [url] String|必填|下载地址
  void updateApp(context, String url) async {
    // 开启下载弹窗
    ProgressDialog pd = ProgressDialog(context: context);

    pd.show(
      max: 100,
      msg: "正在解析文件...",
      progressValueColor: GlobalConfig.theme,
      progressBgColor: Colors.black26,
      progressType: ProgressType.valuable,
    );

    await RUpgrade.upgrade(url,
        fileName: "hdy.apk",
        isAutoRequestInstall: true,
        upgradeFlavor: RUpgradeFlavor.normal);

    RUpgrade.stream.listen((DownloadInfo info) {
      // 正在下载中
      pd.update(value: info.percent.toInt(), msg: "正在下载...");

      // 下载完成关闭，提示窗
      if (info.status == DownloadStatus.STATUS_SUCCESSFUL) {
        setState(() {
          state = 0;
        });
        pd.close();
      }

      // 下载完成关闭，提示窗
      if (info.status == DownloadStatus.STATUS_FAILED) {
        setState(() {
          setState(() {
            state = 1;
          });
        });
        pd.close();
      }
    });
  }

  @override
  void initState() {
    // 监听页面build完成后，进行回调
    WidgetsBinding.instance.addPostFrameCallback(
        (callback) => updateApp(context, Get.arguments["url"]));

    super.initState();
  }
}
